﻿using FAQ_UI.window;
using java.io;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using yzrilyzr.FAQ.constants;
using yzrilyzr.FAQ.protocol;
using yzrilyzr.FAQ.utils;
using yzrilyzr.util;

namespace FAQ_UI
{
	/// <summary>
	/// ChatPage.xaml 的交互逻辑
	/// </summary>
	public partial class ChatPage : Page, MsgPackReceiver, INotifyPropertyChanged
	{
		private Logger logger = new Logger("Chat");
		private FAQID to;
		private List<string> sendFileList = new List<string>();
		private BinMsgPack ReplyMsgPack;

		public bool EnterSend
		{
			get { return FAQUtil.settings.getBoolean(D.SETTINGS, "EnterSend", true); }
			set { FAQUtil.settings.put(D.SETTINGS, "EnterSend", new java.lang.Boolean(value)); FAQUtil.settings.delaySave(1000); }
		}
		public ChatPage()
		{
			InitializeComponent();
			DataContext = this;
			logger.i("init");
			FAQUtil.client.addReceiver(this);
			FAQUtil.eventBus.addReceiver(this);
			sendTextMsgView();
			DragView.Background = Theme.BackBrush;
		}

		public event PropertyChangedEventHandler PropertyChanged;

		public Drawable Avatar
		{ get { return FAQUtil.getAvatar(to); } }

		public string ToDescription
		{ get { return FAQUtil.getDescription(to); } }

		public string ToName
		{ get { return FAQUtil.getCommNameOrName(to); } }

		public List<string> BSendFileListDataSource
		{ get { return sendFileList; } }

		public SendFileListHolder BSendFileListHolder
		{ get { return new SendFileListHolder(); } }

		public void receive(MsgPackTransfer mpt, MsgPack mp)
		{
			int i = mp.getCmd();
			Dispatcher.Invoke(new Action(() =>
			{
				if (i == App.OPEN_CHAT)
				{
					to = mp.getTo();
					logger.i("ChatTo", to);
					FAQUtil.eventBus.asyncSend(new BinMsgPack(App.OPEN_STICKER_TO).setTo(to));

					OnPropertyChanged(nameof(Avatar));
					OnPropertyChanged(nameof(ToName));
					OnPropertyChanged(nameof(ToDescription));
				}
				else if (i == App.CLOSE_STICKER)
				{
					StickerPopup.IsOpen = false;
				}
				else if (i == C.USER_CACHE )
				{
					OnPropertyChanged(nameof(ToName));
					OnPropertyChanged(nameof(Avatar));
					OnPropertyChanged(nameof(ToDescription));
				}else if(i==App.SET_CHAT_REPLY)
				{
					if(!mp.has(K.DATA))
					{
						ReplyMsgPack = null;
						ReplyView.Visibility=Visibility.Collapsed;
					}
					else
					{
						ReplyMsgPack = new BinMsgPack(mp.getData());
						ReplyView.Visibility = Visibility.Visible;
						ReplyView.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(128, 128, 128, 128));
						ReplyText.Text = string.Format("回复：{0}：{1}", FAQUtil.getCommNameOrName(ReplyMsgPack.getFromUser()), ReplyMsgPack.getStrData());
					}
				}
			}));
		}

		protected void OnPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
		}

		private void chatFunction(object sender, MouseButtonEventArgs e)
		{
			string name = ((FrameworkElement)sender).Name;
			if (name == "chatFunctionKey")
			{
				FAQUtil.eventBus.asyncSend(new BinMsgPack(App.OPEN_PUBKEY_SET).setTo(to));
			}
			else if (name == "chatFunction1")
			{
				StickerPopup.IsOpen = true;
				StickerPopup.Focus();
				StickerPopup.Width = ChatMsgListFrame.RenderSize.Width - 20;
				StickerPopup.Height = ChatMsgListFrame.RenderSize.Height - 20;
				StickerPopup.CustomPopupPlacementCallback = new CustomPopupPlacementCallback(placeStickerPopup);
				FAQUtil.eventBus.asyncSend(new BinMsgPack(App.OPEN_STICKER_TO).setTo(to));
			}
			else if (name == "chatFunction2")
			{
				if (TextMsg.Visibility == Visibility.Collapsed) sendTextMsgView();
				else sendFileView();
			}
		}

		private void closePage(object sender, MouseButtonEventArgs e)
		{
			FAQUtil.eventBus.asyncSend(new BinMsgPack(App.CLOSE_CHAT));
		}

		private void openProfile(object sender, MouseButtonEventArgs e)
		{
			new UserProfile(to).Show();
		}

		private void Page_Unloaded(object sender, RoutedEventArgs e)
		{
			//FAQUtil.eventBus.removeReceiver(this);
			//FAQUtil.client.removeReceiver(this);
		}

		private void Page_Loaded(object sender, RoutedEventArgs e)
		{
			FAQUtil.eventBus.addReceiver(this);
			FAQUtil.client.addReceiver(this);
		}

		private CustomPopupPlacement[] placeStickerPopup(Size popupSize, Size targetSize, Point offset)
		{
			CustomPopupPlacement placement1 = new CustomPopupPlacement(new Point(10, -popupSize.Height), PopupPrimaryAxis.Vertical);
			CustomPopupPlacement[] ttplaces = new CustomPopupPlacement[] { placement1 };
			return ttplaces;
		}

		private void Can_Paste_Msg(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
			e.Handled = true;
		}

		private void Paste_Msg(object sender, ExecutedRoutedEventArgs e)
		{
			e.Handled = true;
			string text = Clipboard.GetText();
			if (text != null)
			{
				TextMsg.AppendText(text);
				sendTextMsgView();
			}
			BitmapSource im = Clipboard.GetImage();
			if (im != null)
			{
				byte[] arr = FAQUtil.ToByteArray(new PngBitmapEncoder(), im);
				string path = Path.GetTempFileName();
				Util.write(path, arr);
				sendFileList.Add(path);
				sendFileView();
			}
			System.Console.WriteLine("paste");
		}

		private void SendMsg(object sender, System.Windows.RoutedEventArgs e)
		{
			if (TextMsg.Visibility == Visibility.Visible)
			{
				string msg = TextMsg.Text;
				if (msg != "")
				{
					FAQUtil.client.sendMsg(to, msg,null,ReplyMsgPack);
					FAQUtil.eventBus.asyncSend(new BinMsgPack(App.SET_CHAT_REPLY)); 
					TextMsg.Text = "";
				}
				else
				{
				}
			}
			else if (SendFileGrid.Visibility == Visibility.Visible)
			{
				List<string> strings = new List<string>(sendFileList);
				if (strings.Count == 0)
				{
					sendTextMsgView();
					return;
				}
				sendFileList.Clear();
				sendTextMsgView();
				foreach (var file in strings)
				{
					string mime = MIMEUtil.getMIMEType(new java.io.File(file));
					if (mime.Contains("image"))
					{
						FAQUtil.client.sendPic(to, Util.read(new java.io.FileInputStream(file)), false, false);
					}
					else
					{
						java.io.File ff = new java.io.File(file);
						MsgPack p = FAQUtil.client.getSendFileMsgPack(to, ff, ff.getName(), null);
						p.put(K.LOCALURI, ff.getAbsolutePath());
						if (!p.has(K.DATA))
						{
							FAQUtil.client.setMsgListAppend(to, p);
							FAQUtil.client.post(new BinMsgPack(C.FRONTEND_FROM_ME_UPDATE).put(K.DATA, p));
							FAQUtil.eventBus.post(new BinMsgPack(App.BIGDATA_UPLOAD).put(K.DATA, p));
						}
						else
						{
							FAQUtil.client.send(p);
						}
					}
				}
			}
		}
		private void sendFileView()
		{
			TextMsg.Visibility = Visibility.Collapsed;
			SendFileGrid.Visibility = Visibility.Visible;
			SendFileGrid.Background = Theme.BackBrush;
			ChatPageMainGrid.RowDefinitions[3].MinHeight = 150;
			ChatPageMainGrid.RowDefinitions[3].MaxHeight = 300;
			ChatPageMainGrid.RowDefinitions[3].Height = new GridLength(3, GridUnitType.Star);
			DragFileTip.Visibility = sendFileList.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
			SendFileGrid.notifyDataChanged();
			SendFileGrid.Focus();
		}

		private void sendTextMsgView()
		{
			TextMsg.Visibility = Visibility.Visible;
			SendFileGrid.Visibility = Visibility.Collapsed;
			SendFileGrid.Background = Theme.BackBrush;
			ChatPageMainGrid.RowDefinitions[3].MinHeight = 80;
			ChatPageMainGrid.RowDefinitions[3].MaxHeight = 150;
			ChatPageMainGrid.RowDefinitions[3].Height = new GridLength(1, GridUnitType.Star);
			DragFileTip.Visibility = Visibility.Collapsed;
		}

		private void TextMsg_Drop(object sender, DragEventArgs e)
		{
			var fileItems = e.Data.GetData(DataFormats.FileDrop) as string[];
			if (fileItems != null)
			{
				foreach (var filePath in fileItems)
				{
					sendFileList.Add(filePath);
				}
				sendFileView();
			}
			var p = e.Data.GetData(typeof(MsgPack)) as MsgPack;
			if (p != null)
			{
				int cmd = p.getCmd();
				if (cmd == C.MSG)
				{
					TextMsg.AppendText(p.getStrData());
					sendTextMsgView();
				}
			}
		}

		private void TextMsg_PreviewDragOver(object sender, DragEventArgs e)
		{
			e.Effects = DragDropEffects.Copy;
			e.Handled = true;
		}

		public void onItemClick(object listview, OnItemClickEvent e)
		{
			if (listview == SendFileGrid)
			{
			}
		}

		public class SendFileListHolder : IconGridHolder
		{
			public override ViewHolder newInstance()
			{
				return new SendFileListHolder();
			}

			public override void set(int i, object data, IList datalist)
			{
				FileInfo fileInfo = new FileInfo((string)data);
				Name.Text = fileInfo.Name;
				string mime = MIMEUtil.getMIMEType(new java.io.File(fileInfo.FullName));
				if (mime.Contains("image"))
				{
					Icon.Drawable = FAQUtil.imageCache.get("fileicon" + fileInfo.FullName, new Loader<Drawable>(() =>
					{
						return FAQUtil.getDrawableFile(fileInfo.FullName);
					}));
				}
				else
				{
					Icon.Drawable = FAQUtil.imageCache.get("fileicon" + fileInfo.FullName, new Loader<Drawable>(() =>
					{
						return FAQUtil.Text2Icon("\ue24d", 100);
					}));
				}
			}
		}

		private void dragWindow(object sender, MouseButtonEventArgs e)
		{
			Window.GetWindow(this).DragMove();
		}

		private void TextMsg_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.Key == Key.Enter&&EnterSend)
			{
				e.Handled = true;
				SendMsg(sender, e);
			}

		}

		private void ClearReply(object sender, MouseButtonEventArgs e)
		{
			FAQUtil.eventBus.asyncSend(new BinMsgPack(App.SET_CHAT_REPLY));
		}
	}
}